/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.flink.streaming.runtime.operators.windowing;

import org.apache.flink.streaming.api.operators.Output;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;

import java.util.ArrayList;
import java.util.List;

public class CollectingOutput<T> implements Output<StreamRecord<T>> {
	
	private final List<T> elements = new ArrayList<>();

	private final int timeStampModulus;


	public CollectingOutput() {
		this.timeStampModulus = 0;
	}
	
	public CollectingOutput(int timeStampModulus) {
		this.timeStampModulus = timeStampModulus;
	}

	// ------------------------------------------------------------------------
	
	public List<T> getElements() {
		return elements;
	}
	
	public void waitForNElements(int n, long timeout) throws InterruptedException {
		long deadline = System.currentTimeMillis() + timeout;
		synchronized (elements) {
			long now;
			while (elements.size() < n && (now = System.currentTimeMillis()) < deadline) {
				elements.wait(deadline - now);
			}
		}
	}

	// ------------------------------------------------------------------------
	
	@Override
	public void emitWatermark(Watermark mark) {
		throw new UnsupportedOperationException("the output should not emit watermarks");
	}

	@Override
	public void collect(StreamRecord<T> record) {
		elements.add(record.getValue());
		
		if (timeStampModulus != 0 && record.getTimestamp() % timeStampModulus != 0) {
			throw new IllegalArgumentException("Invalid timestamp");
		}
		synchronized (elements) {
			elements.notifyAll();
		}
	}

	@Override
	public void close() {}
}
